/**
 * @file DrawMode.cpp
 *
 * @date 15/12/2011
 * @author Tales 
 *
 */

#include "DrawMode.hpp"
#include <iostream>
#include "../controller/Editor.hpp"
#include "InfoMode.hpp"
#include "modes.hpp"

namespace yep
{

DrawMode::~DrawMode()
{
}

void DrawMode::handle(Editor & editor, const SDL_Event & event)
{
	Uint32 mod = SDL_GetModState();
	bitset<5> state;
	state[MOD_1] = mod & KMOD_SHIFT;
	state[MOD_2] = mod & KMOD_CTRL;
	state[MOD_3] = mod & KMOD_ALT;
	switch (event.type)
	{
	case SDL_MOUSEBUTTONDOWN:
		if (event.button.button == SDL_BUTTON_LEFT)
		{
			state[BUTTON_LEFT] = true;
			editor.pressed(make_pair(event.button.x, event.button.y), true, state);
		}
		else if (event.button.button == SDL_BUTTON_RIGHT)
		{
			state[BUTTON_RIGHT] = true;
			editor.pressed(make_pair(event.button.x, event.button.y), false, state);
		}
		break;
	case SDL_MOUSEBUTTONUP:
		if (event.button.button == SDL_BUTTON_LEFT)
		{
			state[BUTTON_LEFT] = true;
			editor.released(make_pair(event.button.x, event.button.y), true, state);
		}
		else if (event.button.button == SDL_BUTTON_RIGHT)
		{
			state[BUTTON_RIGHT] = true;
			editor.released(make_pair(event.button.x, event.button.y), false, state);
		}
		break;
	case SDL_MOUSEMOTION:
		state[BUTTON_LEFT] = event.motion.state & SDL_BUTTON_LMASK;
		state[BUTTON_RIGHT] = event.motion.state & SDL_BUTTON_RMASK;
		editor.moved(make_pair(event.motion.x, event.motion.y), make_pair(event.motion.xrel, event.motion.yrel), state);
		break;
	case SDL_KEYDOWN:
		switch (event.key.keysym.sym)
		{
		case SDLK_z:
			if(event.key.keysym.mod & KMOD_CTRL)
			{
				if(event.key.keysym.mod & KMOD_SHIFT)
					editor.redo();
				else
					editor.undo();
			}
			break;
		case SDLK_c:
			if (event.key.keysym.mod & KMOD_CTRL)
				editor.selectToClipboard();
			break;
		case SDLK_v:
			if (event.key.keysym.mod & KMOD_CTRL)
				editor.selectFromClipboard();
			break;
		default:
			if (event.key.keysym.sym >= SDLK_1 && event.key.keysym.sym <= SDLK_9)
			{
				size_t number = event.key.keysym.sym - SDLK_1;
				if (number < editor.getToolCount())
					editor.setTool(number);
			}
			else if (event.key.keysym.sym >= SDLK_F1 && event.key.keysym.sym <= SDLK_F12)
			{
				size_t number = event.key.keysym.sym - SDLK_F1;
				if (number < modes::getCount())
					modes::chooseMode(number);
			}
			break;
		}
		break;
	default:
		break;
	}
}

void DrawMode::logic(Editor & editor)
{
}

void DrawMode::draw(Editor & editor, SDL_Surface *surface)
{
	editor.render(surface);
}

DrawMode & DrawMode::getInstance()
{
	static DrawMode *instance = NULL;
	if (!instance)
	{
		instance = new DrawMode;
	}
	return *instance;
}

DrawMode::DrawMode()
{
}

} /* namespace yep */
